package com.zj.weather.bgviews.light.child;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;

import com.zj.weather.R;
import com.zj.weather.bgviews.light.LightInfo;
import com.zj.weather.utils.DisplayUtils;

import static com.zj.weather.utils.RandomUtils.getRandom;

/**
 * Created by zhaojie on 2018/8/14.
 */

public class SmallLightInfo extends LightInfo {

    private float maxWidth = 320f, minWidth = 170f;
    private float maxHeight = 110f, minHeight = 90f;
    private Drawable drawable;
    private float x, y;
    private float drawableWidth, drawableHeight;

    public SmallLightInfo(float width, float height, float cloudHeight, float maxAlpha, float speed, int branch, int maxShiningCount) {
        super(width, height, cloudHeight, maxAlpha, speed, branch, maxShiningCount);
    }

    @Override
    public void initData(Context context) {
        maxWidth = DisplayUtils.dip2px(context, maxWidth);
        minWidth = DisplayUtils.dip2px(context, minWidth);
        maxHeight = DisplayUtils.dip2px(context, maxHeight);
        minHeight = DisplayUtils.dip2px(context, minHeight);
        drawableWidth = getRandom(minWidth, maxWidth);
        drawableHeight = getRandom(minHeight, maxHeight);
        x = width * getRandom(0.2f, 0.8f);
        y = (cloudHeight - drawableHeight) * getRandom(0.3f, 0.7f);
        drawable = context.getResources().getDrawable(R.mipmap.light_small);
        RectF rectF = new RectF(x - drawableWidth / 2f, y - drawableHeight / 2f, x + drawableWidth / 2f, y + drawableHeight / 2f);
        drawable.setBounds((int) rectF.left, (int) rectF.top, (int) rectF.right, (int) rectF.bottom);
        fraction = -1f;
    }

    @Override
    public boolean draw(Context c, Canvas canvas, float changeAlpha) {
        super.draw(c, canvas, changeAlpha);
        boolean isEnd = false;
        if (isShining && shiningCount < maxShiningCount) {
            int alpha = (int) (255 * changeAlpha);
            drawable.setAlpha(alpha);
            drawable.draw(canvas);
        } else {
            drawable.setAlpha((int) (255f * 0.5f));
            drawable.draw(canvas);
        }
        if (shiningCount % 4 == 0)
            isShining = !isShining;
        shiningCount++;
        boolean isFinishLighting = shiningCount >= maxShiningCount;
        if (isFinishLighting) {
            fraction += 0.23f;
            isEnd = fraction >= 1.0f;
            int alpha = (int) ((1.0f - Math.min(1.0f, Math.max(0.0f, fraction))) * changeAlpha * 255f);
            drawable.setAlpha(alpha);
            drawable.draw(canvas);
        }
        if (isEnd) {
            fraction = 0;
            shiningCount = 0;
        }
        return isEnd;
    }
}
